<template>
  <div class="dialog-role">
    <el-dialog
      :visible.sync="dialogVisible"
      :title="field"
      width="800px"
      @close="handleClose"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="dialog-ruleForm"
      >
        <el-form-item
          label="上级菜单:"
          prop="parentName"
          v-if="ruleForm.parentName"
        >
          <div style="display: flex">
            <el-input
              v-model="ruleForm.parentName"
              clearable
              @focus="
                () => {
                  dialogMenuVisible = true;
                }
              "
            >
            </el-input>
            <div
              style="padding: 0 15px; border-left: 1px solid #dcdfe6"
              @click="
                () => {
                  dialogMenuVisible = true;
                }
              "
            >
              <i class="el-icon-search" style="font-size: 20px"></i>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="菜单类型:" prop="menuType">
          <el-radio-group v-model="ruleForm.menuType">
            <el-radio label="M">目录</el-radio>
            <el-radio label="C">菜单</el-radio>
            <el-radio label="F">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称:" prop="menuName">
          <el-input v-model="ruleForm.menuName" clearable />
        </el-form-item>
        <el-form-item
          label="页面路径:"
          prop="path"
          v-if="ruleForm.menuType != 'F' || ruleForm.menuType == ''"
        >
          <el-input v-model="ruleForm.path" clearable />
        </el-form-item>
        <el-form-item
          label="组件路径:"
          prop="component"
          v-if="ruleForm.menuType != 'F' || ruleForm.menuType == ''"
        >
          <el-input v-model="ruleForm.component" clearable />
        </el-form-item>
        <el-form-item
          label="权限识别:"
          prop="perms"
          v-if="ruleForm.menuType != 'M' || ruleForm.menuType == ''"
        >
          <el-input
            v-model="ruleForm.perms"
            clearable
            :disabled="typeDialog && typeDialog == 'edit'"
          />
        </el-form-item>
        <el-form-item label="显示排序:" prop="orderNum">
          <el-input v-model="ruleForm.orderNum" clearable />
        </el-form-item>
        <el-form-item
          label="选择图标:"
          prop="icon"
          v-if="ruleForm.menuType == 'M' || ruleForm.menuType == ''"
        >
          <el-select
            v-model="ruleForm.icon"
            placeholder="请选择"
            popper-class="icon-select"
          >
            <el-option
              v-for="(item, index) in iconList"
              :key="index"
              :label="item"
              :value="item"
            >
              <div style="display: flex; align-items: center">
                <svg-icon
                  :icon-class="item"
                  style="width: 16px; height: 16px; margin-right: 8px"
                ></svg-icon>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="菜单状态:"
          prop="visible"
          v-if="ruleForm.menuType != 'F' || ruleForm.menuType == ''"
        >
          <el-radio-group v-model="ruleForm.visible">
            <el-radio label="0">显示</el-radio>
            <el-radio label="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="是否刷新:"
          prop="isRefresh"
          v-if="ruleForm.menuType == 'C' || ruleForm.menuType == ''"
        >
          <el-radio-group v-model="ruleForm.isRefresh">
            <el-radio label="1">否</el-radio>
            <el-radio label="0">是</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog width="400px" title="菜单选择" :visible.sync="dialogMenuVisible">
      <div class="menu-permisssion">
        <el-tree
          ref="roleTree"
          :data="treeData"
          node-key="menuId"
          :default-expanded-keys="defaultExpandedKeys"
          :expand-on-click-node="false"
          @node-click="checkNode"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <svg-icon
              :icon-class="getNodeIcon(node)"
              style="width: 16px; height: 14px"
            />
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogMenuVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleParentNode()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { menuAdd, menuEdit, menuList } from "@/api/systemmanagement";
export default {
  name: "ProjectDetail",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    field: {
      type: String,
      default: "",
    },
    menuRow: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      typeDialog: "添加菜单",
      ruleForm: {},
      rules: {
        // 上级菜单校验
        parentName: [
          { required: false, message: "请选择上级菜单", trigger: "change" },
        ],
        // 菜单类型校验
        menuType: [
          { required: true, message: "请选择菜单类型", trigger: "change" },
        ],
        // 菜单名称校验
        menuName: [
          { required: true, message: "请输入菜单名称", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "菜单名称长度为2-50个字符",
            trigger: "blur",
          },
        ],
        // 请求地址校验
        path: [
          { required: true, message: "请输入请求地址", trigger: "blur" },
          {
            max: 200,
            message: "请求地址长度不能超过200个字符",
            trigger: "blur",
          },
        ],
        // 页面路径校验
        component: [
          { required: true, message: "请输入页面路径", trigger: "blur" },
          {
            max: 200,
            message: "页面路径长度不能超过200个字符",
            trigger: "blur",
          },
        ],
        // 权限标识校验
        perms: [
          { required: false, message: "请输入权限标识", trigger: "blur" },
          {
            max: 100,
            message: "权限标识长度不能超过100个字符",
            trigger: "blur",
          },
        ],
        // 显示排序校验
        orderNum: [
          { required: true, message: "请输入显示排序", trigger: "blur" },
          { pattern: /^\d+$/, message: "排序必须为正整数", trigger: "blur" },
        ],
        // 图标校验
        icon: [{ required: false, message: "请选择图标", trigger: "change" }],
        // 菜单状态校验
        visible: [
          { required: false, message: "请选择菜单状态", trigger: "change" },
        ],
        // 是否刷新校验
        isRefresh: [
          { required: false, message: "请选择是否刷新", trigger: "change" },
        ],
      },
      iconList: [
        "home",
        "business",
        "dataCenter",
        "chart",
        "deviceManagement",
        "group",
        "deviceSpread",
        "monitor",
        "person",
        "project",
        "setinterval",
        "systemManagement",
        "version",
        "deviceSpread",
      ],
      collapse: false,
      radio: "",
      dialogMenuVisible: false,
      // 确保 defaultExpandedKeys 在 data 中正确定义
      defaultExpandedKeys: [],
      treeData: [],
      nodeData: {},
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("close", val);
      },
    },
  },
  watch: {
    collapse(val) {
      this.handleCollapseChange(val);
    },
    dialogVisible: {
      handler(val) {
        if (val) {
          // 每次弹窗打开时都重新初始化表单
          this.updateRuleForm();
        }
      },
    },
    // 监听 dialogMenuVisible 变化
    dialogMenuVisible: {
      handler() {
        this.initTree();
        // this.updateRuleForm();
      },
      immediate: true,
    },
    field: {
      handler() {
        this.updateRuleForm();
      },
      immediate: true, // 添加 immediate 确保初始值也被处理
    },
    menuRow: {
      handler(val) {
        if (val && typeof val === "object" && Object.keys(val).length > 0) {
          if (this.field == "添加菜单") {
            console.log(val, "val");
            this.ruleForm.parentId = val.parentId || "0";
            this.ruleForm.parentName = val.menuName || "";
            this.ruleForm.menuId = val.menuId || "0";
          } else {
            this.ruleForm = { ...val };
          }
        } else {
          // 重置表单为初始状态
          this.ruleForm = {
            parentName: "",
            menuName: "",
            menuType: "",
            path: "",
            visible: "0",
            orderNum: "",
            component: "",
            perms: "",
            isRefresh: "1",
            icon: "",
          };
        }
      },
      immediate: true,
    },
  },
  mounted() {
    
  },
  methods: {
    initTree() {
      menuList().then((res) => {
        this.treeData = this.processTreeData(res.data);
      });
    },
    // 递归处理树形数据，添加label字段
    processTreeData(data) {
      if (!Array.isArray(data)) {
        return [];
      }

      return data.map((item) => {
        // 创建新对象，避免直接修改原始数据
        const processedItem = {
          ...item,
          label: item.menuName || item.label || "", // 使用menuName作为label
        };

        // 如果有子节点，递归处理
        if (processedItem.children && processedItem.children.length > 0) {
          processedItem.children = this.processTreeData(processedItem.children);
        }

        return processedItem;
      });
    },
    // 提交表单时的校验
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 校验通过，执行提交逻辑
          this.handleSubmit();
        } else {
          this.$message.error("请完善表单信息");
          return false;
        }
      });
    },
    // 处理提交逻辑
    handleSubmit() {
      let data = {
        menuName: this.ruleForm.menuName,
        menuType: this.ruleForm.menuType,
        path: this.ruleForm.path,
        visible: this.ruleForm.visible,
        orderNum: this.ruleForm.orderNum,
        component: this.ruleForm.component,
        perms: this.ruleForm.perms,
        isRefresh: this.ruleForm.isRefresh,
        icon: this.ruleForm.icon,
      };
      // 根据添加或编辑模式调用不同接口
      if (this.field == "添加菜单") {
        data.parentId = this.ruleForm.menuId || "0";
        menuAdd(data).then((response) => {
          if (response.code === 0) {
            this.$message.success("添加成功");
            this.dialogVisible = false;
            this.$emit("success");
          } else {
            this.$message.error(response.msg || "添加失败");
          }
        });
      } else {
        data.menuId = this.ruleForm.menuId;
        data.parentId = this.ruleForm.parentId;
        // 编辑逻辑
        menuEdit(data).then((response) => {
          if (response.code === 0) {
            this.$message.success("修改成功");
            this.dialogVisible = false;
            this.$emit("success");
          } else {
            this.$message.error(response.msg || "修改失败");
          }
        });
      }
    },
    handleClose() {
      this.dialogVisible = false;
      this.$emit("close");
    },
    updateRuleForm() {
      const val = this.menuRow;
      if (val && typeof val === "object" && Object.keys(val).length > 0) {
        if (this.field == "添加菜单") {
          this.ruleForm.parentId = val.menuId || 0;
          this.ruleForm.parentName = val.menuName || "";
          // 确保其他字段被重置
          Object.assign(this.ruleForm, {
            menuName: "",
            menuType: "",
            path: "",
            visible: "0",
            orderNum: "",
            component: "",
            perms: "",
            isRefresh: "1",
            icon: "",
          });
        } else {
          this.ruleForm = { ...val };
        }
      } else {
        // 重置表单为初始状态
        this.ruleForm = {
          parentName: "",
          menuName: "",
          menuType: "",
          path: "",
          visible: "0",
          orderNum: "",
          component: "",
          perms: "",
          isRefresh: "1",
          icon: "",
        };
      }
      // 重置表单校验状态
      this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.clearValidate();
        }
      });
    },
    handleCollapseChange(val) {
      if (val) {
        this.expandAllNodes(true);
      } else {
        this.expandAllNodes(false);
      }
    },

    expandAllNodes(expand) {
      const nodes = this.$refs.roleTree.store._getAllNodes();
      nodes.forEach((node) => {
        node.expanded = expand;
      });
    },
    checkNode(node) {
      this.nodeData = node;
    },
    handleParentNode() {
      this.ruleForm.parentName = this.nodeData.menuName;
      this.ruleForm.parentId = this.nodeData.menuId;
      this.dialogMenuVisible = false;
      setTimeout(() => {
        this.nodeData = {};
      }, 100);
    },

    getNodeIcon(node) {
      if (node && node.childNodes && node.childNodes.length > 0) {
        return "fold";
      } else {
        return "file";
      }
    },
  },
};
</script>

<style scoped lang="scss">
.dialog-role {
  .dialog-ruleForm {
    width: 80%;
    line-height: 60px;
    margin: 0 auto;
    .el-radio-group {
      margin-left: 10px;
    }
  }
  .menu-permisssion {
    border: 1px solid #dcdfe6;
    padding: 15px;
    border-radius: 4px;
  }
}
</style>
<style lang="scss">
.icon-select {
  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover,
  .el-select-dropdown__item.selected {
    background-color: #fff;
    color: #606266;
  }
  .el-select-dropdown__list {
    display: grid;
    grid-template-columns: repeat(8, 1fr);
    .el-select-dropdown__item {
      display: flex;
      align-items: center;
      .svg-icon {
        width: 20px !important;
        height: 20px !important;
        margin: 0 !important;
      }
    }
  }
}
</style>
